'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：requestsAndurllib.request.py
#日期：2018-12-13
#备注： requests与urllib.request模块的区别 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import requests
import urllib.request


url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
api ='http://open.iciba.com/dsapi/'
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'
    }
form_data = {
    "i": "word",
    "from": "AUTO",
    "to": "AUTO",
    "smartresult": "dict",
    "doctype": "json",
    "version": "2.1",
    "keyfrom": "fanyi.web",
    "action": "FY_BY_REALTIME",
    "typoResult": "false"
}


req1 = requests.get(url,headers=headers)
req_api = requests.get(api,headers=headers)

print(type(req1),type(req1.text),req1.text)              # requests.get().text是str类型
print(type(req1.content),req1.content)                   # requests.get().content是bytes类型
print("与直接req1.text一致",req1.content.decode())
print("接口返回json格式",req_api.json())                  # 接口返回格式需要用requests.get().json()


# POST发送的data必须为bytes或bytes类型的可迭代对象，不能是字符串
form_data = urllib.parse.urlencode(form_data).encode()
# urllib.request.Request()只是一个请求：
req2 = urllib.request.Request(url,data=form_data,headers=headers)
print("请求对象类型：",type(req2))


req3 = urllib.request.urlopen(url)      # 不可以伪装你的User Agent,可以通过urllib.request.Request()伪装
print("响应对象类型：",type(req3),req3.status)           # http.client.HTTPResponse
print(req3.getheaders())                # 响应的信息集合
print(req3.read().decode("utf-8"))      # urllib.request.urlopen().read().decode("utf-8")相当于requests.get().text

req4 = urllib.request.urlopen(req2)     # 参数可以直接是一个请求
print("直接一个请求：",req4.read().decode("utf-8"))
